package com.dailyblue.project.estate.letter.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dailyblue.project.estate.commons.bean.Letter;
import com.dailyblue.project.estate.commons.handler.LetterException;
import com.dailyblue.project.estate.commons.mapper.LetterMapper;
import com.dailyblue.project.estate.commons.mapper.OwnerMapper;
import com.dailyblue.project.estate.commons.util.JsonResult;
import com.dailyblue.project.estate.commons.util.ResultTool;
import com.dailyblue.project.estate.letter.service.LetterService;
import jakarta.annotation.Resource;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class LetterServiceImpl extends ServiceImpl<LetterMapper, Letter> implements LetterService {
    @Resource
    private LetterMapper letterMapper;

    @Override
    public JsonResult addLetter(Letter letter) {
        boolean b = save(letter);
        if (!b) {
            throw new LetterException("添加失败");
        }
        return ResultTool.success("success");
    }

    @Override
    public JsonResult findOneLetter(String letterId) {
        Letter letter = getById(letterId);
        return ResultTool.success(letter);
    }

    @Cacheable(cacheNames = "findAllLetters")
    public JsonResult findAllLetters() {
        List<Letter> list = list();
        return ResultTool.success(list);
    }

    @CacheEvict(cacheNames = "findAllLetters", allEntries = true)
    public JsonResult deleteLetter(String letterId) {
        boolean b = removeById(letterId);
        if (!b) {
            return ResultTool.fail(201, "删除失败");
        }
        return ResultTool.success("删除成功");
    }

    @CacheEvict(cacheNames = "findAllLetters", allEntries = true)
    public JsonResult updateLetter(Letter letter) {
        UpdateWrapper<Letter> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", letter.getId());
        updateWrapper.set("community_id", letter.getCommunityId());
        updateWrapper.set("community_name", letter.getCommunityName());
        updateWrapper.set("origin", letter.getOrigin());
        updateWrapper.set("title", letter.getTitle());
        updateWrapper.set("content", letter.getContent());
        updateWrapper.set("create_time", letter.getCreateTime());
        updateWrapper.set("update_time", letter.getUpdateTime());
        updateWrapper.set("status", letter.getStatus());
        int i = letterMapper.update(updateWrapper);
        if (i <= 0) {
            return ResultTool.fail(201, "更新失败");
        }
        return ResultTool.success("更新成功");
    }
}
